package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.bean.VoiceBean;
import com.xn.app.muying.fragment.HomeFragment;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.MyMediaPlayer;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.RoundImageView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Request;

/**
 * 语音解答-语音详情页
 * Created by gaoge on 2017/8/12.
 */

public class VoiceSolutionDetailActivity extends BaseActivity implements View.OnClickListener {

    //标题
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //医生大头像
    private RoundImageView mimage = null;
    //医生小头像
    private RoundImageView mimg = null;
    //医生姓名
    private TextView mname = null;
    //医院
    private TextView mhospitalname = null;
    //职称
    private TextView mprofessionaltitle = null;
    //简介
    private TextView mdetails = null;
    //问题
    private TextView mtitle = null;
    //语音
    private ImageView mvoice = null;
    //语音动画
    private View mwifi_loading = null;
    //语音时长
    private TextView mtime = null;
    //线条
    private View xian1 = null;
    //参考文献
//    private TextView mname=null;
    //布局文件
    private LinearLayout linearlayout = null;
    //加载框
    AlertDialog dialog;
    //数据
    VoiceBean voiceBean = null;
    //播放器类
    public static MyMediaPlayer mediaPlayer = null;
    //记录暂停还是播放
    private boolean voiceLean = false;
    //记录语音时长
    private int voice_time = 0;
    Timer timer = null;
    //图片加载
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //语音播放动画
    private AnimationDrawable animation = null;
    //扣费用
    private int pic = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.voice_solution_detail_activity);
        //初始化组件
        init();
    }

    /**
     * 初始化组件
     */
    private void init() {
        //加载并缓存图片
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.home_doctor_moren) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.home_doctor_moren) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        //语音播放动画
        animation = (AnimationDrawable) getResources().getDrawable(R.drawable.wifi_drawable);
        //初始化组件
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        mimage = (RoundImageView) findViewById(R.id.image);
        mimg = (RoundImageView) findViewById(R.id.img);
        mname = (TextView) findViewById(R.id.name);
        mhospitalname = (TextView) findViewById(R.id.hospitalname);
        mprofessionaltitle = (TextView) findViewById(R.id.professionaltitle);
        mdetails = (TextView) findViewById(R.id.details);
        mtitle = (TextView) findViewById(R.id.title);
        mvoice = (ImageView) findViewById(R.id.voice);
        mwifi_loading = (View) findViewById(R.id.wifi_loading);
        mtime = (TextView) findViewById(R.id.time);
        xian1 = (View) findViewById(R.id.xian1);
        linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
        //设置标题
        title_name.setText("问题详情");
        //添加点击事件
        img_back.setOnClickListener(this);
        mvoice.setOnClickListener(this);
        //判断网络状态
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            //下载数据
            downloadData();
        }
    }

    /**
     * 下载数据
     */
    private void downloadData() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.getVoiceSolutionID(getIntent().getIntExtra("id", 0))).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    int code = response.code();
                    if (code == 200 || code == 204) {
                        onJsonData(bodys);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 数据解析
     *
     * @param bodys 数据
     */
    private void onJsonData(String bodys) {
        try {
            //解析数据
            JSONObject jsonObject = new JSONObject(bodys);
            int id = jsonObject.getInt("id");
            String title = jsonObject.getString("title");
            String lable = jsonObject.getString("lable");
            String author = jsonObject.getString("author");
            int price = jsonObject.getInt("price");
            int frequencyId = jsonObject.getInt("frequencyId");
            String reference = jsonObject.getString("reference");
            boolean isPresent = jsonObject.getBoolean("isPresent");
            String remainingTimes = jsonObject.getString("remainingTimes");
            int doctorId = jsonObject.getInt("doctorId");
            //获取语音信息
            JSONObject jsonObject1 = new JSONObject(jsonObject.getString("frequency"));
            String frequencyName = jsonObject1.getString("frequencyName");
            String frequencyUploadDate = jsonObject1.getString("frequencyUploadDate");
            String frequencyUrl = jsonObject1.getString("frequencyUrl");
            int playTime = jsonObject1.getInt("playTime");
            voice_time = playTime + 5;
            String playDate = jsonObject1.getString("playDate");
            //获取医生信息
            JSONObject jsonObject2 = new JSONObject(jsonObject.getString("doctor"));
            String name = jsonObject2.getString("name");
            String photoUrl = jsonObject2.getString("photoUrl");
            String professionalTitle = jsonObject2.getString("professionalTitle");
            String primaryDepartmentName = jsonObject2.getString("primaryDepartmentName");
            String primaryHospitalName = jsonObject2.getString("primaryHospitalName");
            String expertise = jsonObject2.getString("expertise");
            String expertise2 = jsonObject2.getString("expertise2");
            String expertise3 = jsonObject2.getString("expertise3");
            String expertiseInput = jsonObject2.getString("expertiseInput");
            boolean isDeleted = jsonObject2.getBoolean("isDeleted");
            String doctorInfoId = jsonObject2.getString("doctorInfoId");
            //封装数据
            voiceBean = new VoiceBean();
            voiceBean.setId(id);
            voiceBean.setTitle(title);
            voiceBean.setLable(lable);
            voiceBean.setAuthor(author);
            voiceBean.setPrice(price);
            voiceBean.setFrequencyId(frequencyId);
            voiceBean.setFrequencyName(frequencyName);
            voiceBean.setFrequencyUploadDate(frequencyUploadDate);
            voiceBean.setFrequencyUrl(frequencyUrl);
            voiceBean.setPlayDate(playDate);
            voiceBean.setPlayTime(playTime);
            voiceBean.setDoctorId(doctorId);
            voiceBean.setName(name);
            voiceBean.setPhotoUrl(photoUrl);
            voiceBean.setProfessionalTitle(professionalTitle);
            voiceBean.setPrimaryDepartmentName(primaryDepartmentName);
            voiceBean.setPrimaryHospitalName(primaryHospitalName);
            voiceBean.setExpertise(expertise);
            voiceBean.setExpertise2(expertise2);
            voiceBean.setExpertise3(expertise3);
            voiceBean.setExpertiseInput(expertiseInput);
            voiceBean.setDeleted(isDeleted);
            voiceBean.setDoctorInfoId(doctorInfoId);
            voiceBean.setReference(reference);
            voiceBean.setPresent(isPresent);
            voiceBean.setRemainingTimes(remainingTimes);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mname.setText(voiceBean.getName());
                    mhospitalname.setText(voiceBean.getPrimaryHospitalName());
                    if (voiceBean.getProfessionalTitle() != null && voiceBean.getProfessionalTitle().length() > 0) {
                        xian1.setVisibility(View.VISIBLE);
                    }
                    mprofessionaltitle.setText(voiceBean.getProfessionalTitle());
                    mdetails.setText(voiceBean.getExpertiseInput());
                    mtitle.setText(voiceBean.getTitle());
                    mtime.setText(DateUtils.getTime(voice_time));

                    imageLoader.displayImage(voiceBean.getPhotoUrl(), mimg, options);
//                    imageLoader.displayImage(voiceBean.getPhotoUrl(), mimage, options);

                    linearlayout.setVisibility(View.VISIBLE);
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            });
        } catch (Exception e) {
//            e.printStackTrace();
        }

    }

    /**
     * 点击事件
     *
     * @param v 控件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回键
            case R.id.img_back:
                finish();
                break;
            //播放
            case R.id.voice:
                    if (pic == 0) {
                        AppConstant.setAnswerTimes_1(VoiceSolutionDetailActivity.this);
                        pic++;
                    }
                    mwifi_loading.setBackgroundResource(R.drawable.wifi5);
                    if (!voiceLean) {
                        mwifi_loading.setBackgroundDrawable(animation);
                        animation.start();
                        if (mediaPlayer == null) {
                            mediaPlayer = new MyMediaPlayer();
                        }
                        mediaPlayer.createNetMp3(voiceBean.getFrequencyUrl(), voiceBean.getFrequencyId());
                        mediaPlayer.startNetMp3();
                        voiceLean = true;
                        stratTimer();
                    } else {
                        voiceLean = false;
                        animation.stop();
                        mediaPlayer.pauseNetMp3();
                        timer.cancel();
                    }
                break;
        }
    }

    public void stratTimer() {
        if (timer != null) {
            timer.cancel();
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {      // UI thread
                    @Override
                    public void run() {
                        try {
                            if (voice_time > 1) {
                                voice_time--;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mtime.setText(DateUtils.getTime(voice_time));
                                    }
                                });
                            } else {
                                voice_time++;
                                if (mediaPlayer == null) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            voiceLean = false;
                                            animation.stop();
                                            timer.cancel();
                                            voice_time = voiceBean.getPlayTime() + 5;
                                            mtime.setText(DateUtils.getTime(voice_time));
                                            mwifi_loading.setBackgroundResource(R.drawable.wifi5);
                                        }
                                    });
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
        }, voice_time, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (timer != null) {
                timer.cancel();
            }

            if (animation != null) {
                animation.stop();
            }
            mediaPlayer.stopNetMp3();
        }
    }
}
